﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.IO;
using System.IO.Packaging;
using System.Data;
using ET.ScoreTeacherClient.Print;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// PrintPreview.xaml 的交互逻辑
    /// </summary>
    public partial class PrintPreview : Window
    {
        public PrintPreview()
        {
            InitializeComponent();
        }
        // 委托
        private delegate void LoadXpsMethod();
        //文件流
        private readonly FlowDocument doc;

        /// <summary>
        /// 含参构造函数
        /// </summary>
        /// <param name="strTmplName"></param>
        /// <param name="data"></param>
        /// <param name="title"></param>
        /// <param name="renderer"></param>
        public PrintPreview(string strTmplName, DataTable data, string title, IDocumentRenderer renderer = null)
            : this()
        {
            doc = (FlowDocument)Application.LoadComponent(new Uri(strTmplName, UriKind.RelativeOrAbsolute));
            doc.PagePadding = new Thickness(50);
            if (renderer != null)
            {
                renderer.Render(doc, data, title);
            }
            Dispatcher.BeginInvoke(new LoadXpsMethod(LoadXps), DispatcherPriority.ApplicationIdle);

        }
        public void LoadXps()
        {
            //构造一个基于内存的xps document
            MemoryStream ms = new MemoryStream();
            Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            Uri DocumentUri = new Uri("pack://InMemoryDocument.xps");
            PackageStore.RemovePackage(DocumentUri);
            PackageStore.AddPackage(DocumentUri, package);
            XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri);

            //将flow document写入基于内存的xps document中去
            XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
            writer.Write(((IDocumentPaginatorSource)doc).DocumentPaginator);

            //获取这个基于内存的xps document的fixed document
            docViewer.Document = xpsDocument.GetFixedDocumentSequence();

            //关闭基于内存的xps document
            xpsDocument.Close();
        }
        /// <summary>
        /// DataTable打印
        /// </summary>
        /// <param name="data">DataTable类型数据</param>
        /// <param name="title">string类型标题</param>
        public static void Show(DataTable data, string title)
        {
            PrintPreview previewWnd = new PrintPreview("Print\\FlowDocument.xaml", data, title, new DocumentRenderer());
            previewWnd.ShowDialog();
        }

    }
}
